package com.rory.controller.back.form;

import com.rory.controller.BaseController;
import com.rory.controller.interceptor.Login;
import com.rory.entity.expand.MenuModel;
import com.rory.entity.generate.Menu;
import com.rory.entity.generate.User;
import com.rory.entity.generate.UserInfo;
import com.rory.service.serviceInterface.LoginService;
import com.rory.service.serviceInterface.MenuService;
import com.rory.service.serviceInterface.UserInfoService;
import com.rory.util.IpMacUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * class: LoginController.
 * Created by Rory on 2016/11/22.
 * use:  .
 * other:  .
 */
@Controller
public class LoginController extends BaseController{

    @Autowired
    private LoginService loginService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserInfoService userInfoService;

    //    @RequestParam(required=false) //参数可以为空

    /**
     * 登录方法
     * @param userName     用户名
     * @param userPassword 密码
     * @param code         验证码
     * @return 结果
     */
    @RequestMapping("login")
    public String login(String userName, String userPassword, @RequestParam(required = false) String code) throws Exception{
        User user = loginService.userLogin(userName,userPassword);
        getSession().setAttribute("user", user);
        logger.info("有用户开始登录/: IP:"+ IpMacUtil.getIpAddress() + " / MAC:" + IpMacUtil.getMacAddress());
        return "redirect:/ main";
    }

    /**
     * 进入index页面
     * @return
     */
    @RequestMapping("main")
    @Login
    public String toIndex(){
        User user = (User) getSession().getAttribute("user");
        getSession().setAttribute("userInfo", getIndexUserInfo(user.getUserInfoId()));
        getSession().setAttribute("menu", getIndexMenu(user.getRoleId()));
        return "back/main";
    }

    /**
     * 根据用户加载用户详细
     * @param userInfoId 用户详细id
     * @return
     */
    private UserInfo getIndexUserInfo(Integer userInfoId){
        if(getSession().getAttribute("userInfo") != null){
            return (UserInfo) getSession().getAttribute("userInfo");
        }
        return userInfoService.getUserInfoById(userInfoId);
    }

    /**
     * 根据角色加载菜单
     * @param roleId 角色id
     * @return
     */
    private List<MenuModel> getIndexMenu(Integer roleId){
        if(getSession().getAttribute("menu") != null){
            return (List<MenuModel>) getSession().getAttribute("menu");
        }
        return menuService.loadMenu(roleId);
    }

}
